<script setup lang="ts">
import { ref } from 'vue';
import VuePdfEmbed from 'vue-pdf-embed';

import { Page } from '@vben/common-ui';
import { baselineRotate, downloadIcon, printIcon } from '@vben/icons';

defineOptions({
  name: 'Pdf',
});
const pdfRef = ref<any>();
const pageCount = ref(1);
const loading = ref(true);
const currentPage = ref(1);
const currentRotation = ref(0);
const showAllPages = ref(false);
const rotations = [0, 90, 180, 270];

const source =
  'https://xiaoxian521.github.io/hyperlink/pdf/Cookie%E5%92%8CSession%E5%8C%BA%E5%88%AB%E7%94%A8%E6%B3%95.pdf';

const handleDocumentRender = () => {
  loading.value = false;
  pageCount.value = pdfRef.value.doc.numPages;
};

const showAllPagesChange = () => {
  currentPage.value = showAllPages.value ? 0 : 1;
};

const onPrint = () => {
  // 如果在打印时，打印页面是本身的两倍，在打印配置 页面 设置 仅限页码为奇数的页面 即可
  pdfRef.value.print();
};
const handleDownload = () => {
  pdfRef.value.download();
};
</script>

<template>
  <Page auto-content-height>
    <div
      class="flex h-full flex-col"
      v-loading="loading"
      element-loading-text="加载中"
    >
      <div class="flex h-9 items-center justify-between">
        <div v-if="showAllPages" class="ml-1.25 text-xl font-medium">
          共{{ pageCount }}页
        </div>
        <div v-else>
          <el-pagination
            v-model:current-page="currentPage"
            background
            layout="prev, slot, next"
            :page-size="1"
            :total="pageCount"
          >
            {{ currentPage }} / {{ pageCount }}
          </el-pagination>
        </div>
        <div class="flex w-[200px] items-center justify-between">
          <el-checkbox v-model="showAllPages" @change="showAllPagesChange">
            显示所有页面
          </el-checkbox>
          <baselineRotate
            v-tippy="{
              content: '旋转',
              theme: 'dark',
            }"
            class="size-5 cursor-pointer outline-none"
            @click="
              currentRotation === 3
                ? (currentRotation = 0)
                : (currentRotation += 1)
            "
          />
          <printIcon
            v-tippy="{
              content: '打印',
              theme: 'dark',
            }"
            class="size-5 cursor-pointer outline-none"
            @click="onPrint"
          />
          <downloadIcon
            v-tippy="{
              content: '下载',
              theme: 'dark',
            }"
            class="size-5 cursor-pointer outline-none"
            @click="handleDownload"
          />
        </div>
      </div>
      <el-scrollbar>
        <VuePdfEmbed
          ref="pdfRef"
          :rotation="rotations[currentRotation]"
          :page="currentPage"
          :source="source"
          @rendered="handleDocumentRender"
        />
      </el-scrollbar>
    </div>
  </Page>
</template>
